
package dao;

import entities.Report;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public class ReportDAO implements Serializable {
    
    private EntityManagerFactory emf;

    public ReportDAO(String persistenceUnit) {
        this.emf = Persistence.createEntityManagerFactory(persistenceUnit);
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Report report) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(report);
            em.getTransaction().commit();
        } finally {
            if (em != null) 
                em.close();
        }
    }
    
    public List<Report> getReports(){
        EntityManager em = getEntityManager();
        Query query=em.createNamedQuery("Report.findAll");
        List<Report> reports;
        try {
            reports=query.getResultList();
        } catch (Exception e) {
            reports=new ArrayList<>();
        } finally {
            em.close();
        }
        return reports;
    }

    public Report findReport(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Report.class, id);
        } finally {
            em.close();
        }
    }

    public int getReportCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Report> rt = cq.from(Report.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}